﻿
//websocket 定义
var webSocket = function(onmessage,open,closeCb,parentDiv) {
	this.ws = null;
	this.options={url:wsUrl,onmessage:onmessage,open:open,closeCb:closeCb,parentDiv:parentDiv};
	this.normalClose = false;
	this.init(wsUrl,onmessage,open,closeCb,parentDiv);
	return this;
};
webSocket.prototype={
		reconnectTime:10*1000,
		hbTimerRectonnect:null,
		hbHeartbeat:null,
		bOpen:false,
		reConnect:function(){
			console.log("reConnect hbTimerRectonnect:"+this.hbTimerRectonnect);
			console.log("reConnect bOpen:"+this.bOpen);
			if(this.hbTimerRectonnect == null && this.bOpen == false){
				console.log("reConnect init hbTimerRectonnect");
				var Option = this.options;
				var that = this;
				this.hbTimerRectonnect = window.setInterval(function(){
					//ws.send(1);
					console.log("reConnect");
					//重新连接
					try{
						that.ws.close();
						that.ws = null;
					}catch (e) {
						console.log("连接以关闭");
					}
					that.init(that.options["url"],that.options["onmessage"],that.options["open"],that.options["closeCb"],that.options["parentDiv"]);
				}, this.reconnectTime);
			}
		},
		/**
		 * 发送心跳数据到后端
		 */
		_sendHeartbeat:function(isStart){
			if(true == isStart){  //开始发送心跳
				var msgInfo = JSON.stringify(this.createWebSocketMsgInfo("HB"));
				var that = this;
				//循环发送心跳
				this.hbHeartbeat = window.setInterval(function(){
					that._sendMsg(msgInfo);
					console.log(msgInfo);
				}, this.reconnectTime);
			}else{
				window.clearInterval(this.hbHeartbeat);
				this.hbHeartbeat=null;
			}
		},
		stopReConnect:function(){
			console.log("stopReConnect hbTimerRectonnect:"+this.hbTimerRectonnect);
			if(this.hbTimerRectonnect!=null){
				window.clearInterval(this.hbTimerRectonnect);
				this.hbTimerRectonnect=null;
			}
		},
		init:function(url,onmessage,open,closeCb,parentDiv){
			var that = this;
			//初始化websocket连接
			try{
				this.ws = new SockJS(url) ;   //初始化 websocket
				//当打开Socket连接时调用
				this.ws.onopen = function(e){
					//连接成功时停止重连
					that.stopReConnect();
					//打开心跳发送
					that._sendHeartbeat(true);
					that.bOpen = true;
					websocketFunManager.addWebSocket(parentDiv,that);
					if(null != open && undefined != open && typeof open =="function"){
						open(e);  //执行回调
					}
				}
				//当有数据推送到前端时调用
				this.ws.onmessage = onmessage;
				//当websocket断开时调用
				this.ws.onclose = function(e){
					console.log('Info: connection closed.');
					//关闭心跳发送
					that._sendHeartbeat();
					if(false == that.normalClose){  //非正常断开设置自动重连
						that.bOpen = false;
						//如断开自动重连
						that.reConnect();
						if(null != closeCb && undefined != closeCb && typeof closeCb =="function"){
							closeCb(e);  //执行回调
						}
					}else{
						that.ws = null;
					}
				}
			}catch (e) {
				console.log("connection error");
			}
		},
		/**
		 * 断开当前websocket连接
		 */
		closeWebSocket:function(){
			this.normalClose = true;
			this.stopReConnect();   //停止重连
			this._sendHeartbeat();  //停止发送心跳
			this.ws.close();        //关闭socket
		},
		/**
		 * 内部类使用，不了解格式的请调用sendMsgToWebSocket
		 */
		_sendMsg:function(msg){
			//this.ws.send(msg);
			if(!this.bOpen){
				console.log("websocket is not Connect！！");
				return false;
			}
			if(isEmpty(msg)){return false;}
			this.ws.send(msg);
			return true;
		},
		/**
		 * 浏览器发送消息到websocket后台
		 */
		sendMsgToWebSocket:function(data,cmdType,topic){
			if(isEmpty(data)){return null;}
			var	msgInfo = this.createWebSocketMsgInfoCmd("SENDMSG",data);
			if(!isEmpty(cmdType)){
				msgInfo["cmdType"] = cmdType;
			}
			if(!isEmpty(topic)){
				msgInfo["topics"] = topic.constructor != Array ? [topic] : topic;
			}
			this._sendMsg(JSON.stringify(msgInfo));
			return msgInfo;
		},
		/**
		 * 订阅topics通道
		 */
		registerTopics:function(topics){
			if(isEmpty(topics)) return;
			//topics注册统一到后台都是json数组
			if(topics.constructor != Array){
				var tps = new Array();
				tps.push(topics);
				topics = tps;
			}
			var msgInfo = this.createWebSocketMsgInfo("SUBSCRIBE", topics);
			return this._sendMsg(JSON.stringify(msgInfo));
		},
		/**
		 * 退订topics通道
		 */
		logoutTopics:function(topics){
			if(isEmpty(topics)) return;
			//topics注册统一到后台都是json数组
			if(topics.constructor != Array){
				var tps = new Array();
				tps.push(topics);
				topics = tps;
			}
			var msgInfo = this.createWebSocketMsgInfo("UNSUBSCRIBE", topics);
			return this._sendMsg(JSON.stringify(msgInfo));
		},
		/**
		 * 创建命令对象
		 */
		createWebSocketMsgInfoCmd:function(msgType,data){
			return this.createWebSocketMsgInfo(msgType, null, data)
		},
		/**
		 * 创建通讯对象
		 */
		createWebSocketMsgInfo:function(msgType,topics,data){
			var msgInfo = {};
			msgInfo["msgType"] = msgType;
			//注册的Topic
			msgInfo["topics"] = topics
			//内容
			msgInfo["data"] = data;
			//流水号
			msgInfo["serialNumber"] = new Date().pattern("yyyyMMddHHmmssS") + parseInt((Math.random()*1000));
			return msgInfo;
		}
};